import { ElMessageBox, ElMessageBoxOptions } from 'element-plus'
import { h } from 'vue'

/**二次确认消息盒子消息模板 */
const confirmTipMsgBoxTmplate:Record<string, any> = {
  /**
   * 普通模板
   * @param param0
   * @returns 
   */
  norm: ({top, btm}: {top: string, btm?: string}) => {
    const child = [h('div', null, top)]
    if (btm) {
      child.push(h('p', { style: 'color: #344156;line-height: 1;font-size:14px;margin-top: 8px' }, btm))
    }
    return h('div', null, child)
  }
}

export type DelMsgBoxOpts = ElMessageBoxOptions & {
  confirmCallback?: () => Promise<boolean> | boolean
  template?: {
    name: string,
    bind?: any
  }
}

/**
 * 二次确认消息盒子
 * @param opts
 */
export const confirmTipMsgBox = (options?:DelMsgBoxOpts) => {
  const opts:DelMsgBoxOpts = options || {}
  return new Promise((resolve, reject) => {
    const options: ElMessageBoxOptions = {
      ...opts,
      title: opts.title || '',
      confirmButtonText: opts.confirmButtonText || '删除',
      cancelButtonText: opts.cancelButtonText || '取消',
      type: 'warning',
      buttonSize: 'large',
      draggable: true,
      customClass: opts.customClass ? `custom-message-box ${opts?.customClass}` : 'custom-message-box',
    }
    if (opts.confirmCallback) {
      options.beforeClose = async (action, _instance, done) => {
        if (action === 'confirm') {
          if(opts.confirmCallback && await opts.confirmCallback()) {
            done()
          }
        } else {
          done()
        }
      }
    }
    let message:any = '确定删除?'
    if (opts.message) {
      message = opts.message
    } else if (opts.template) {
      message = confirmTipMsgBoxTmplate[opts.template.name](opts.template.bind)
    }
    ElMessageBox.confirm(
      message,
      options
    ).then(() => {
      resolve('confirm')
    }).catch(() => {
      reject('cancel')
    })
  })
}